package com.sp.business.normalization.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;

import com.sp.generated.xml.firemon.Interface;
import com.sp.generated.xml.firemon.Route;
import com.sp.generated.xml.firemon.RouteCollection;
import com.sp.generated.xml.firemon.StringProperty;

/**
 * Route key generator that treats route identity as composed of destination, gateway, and interface 
 */
public class RouteKeyGenerator
{

  public static void generateRouteKeys(final RouteCollection previous, final RouteCollection current)
  {
    final Map<String, Route> previousMap = new HashMap<String, Route>();

    if (previous != null)
    {
      for (final Route route : previous.getRoutes())
      {
        String guid = route.getUID();
        if (StringUtils.isBlank(guid) || !NormalizationUtil.isStringUUID(guid))
        {
          guid = String.format("{%s}", UUID.randomUUID().toString().toUpperCase());
          route.setUID(guid);
          route.setXsid("Route" + guid.replaceAll("\\{", "").replaceAll("\\}", ""));
        }

        previousMap.put(mapKeyFor(route), route);
      }
    }

    if (current != null)
    {
      for (final Route route : current.getRoutes())
      {
        final String key = mapKeyFor(route);
        final Route previousMatch = previousMap.remove(key);
        copyUID(previousMatch, route);
      }
    }

  }

  protected static String copyUID(Route previous, Route current)
  {
    String guid = null;

    if (previous != null)
    {
      guid = previous.getUID();
    }

    if (StringUtils.isBlank(guid) || !NormalizationUtil.isStringUUID(guid))
    {
      guid = String.format("{%s}", UUID.randomUUID().toString().toUpperCase());
    }

    current.setUID(guid);

    current.setXsid("Route" + guid.replaceAll("\\{", "").replaceAll("\\}", ""));

    return guid;
  }

  private static String mapKeyFor(Route route)
  {
    final String destination = StringUtils.trimToEmpty(NormalizationUtil.getValue(route.getDestination()));
    
    final String gateway = StringUtils.trimToEmpty(NormalizationUtil.getValue(route.getGateway()));
    
    final String interfaceName = route.getInterface() == null || route.getInterface().getInterfaceObject() == null ? ""
        : ((Interface) route.getInterface().getInterfaceObject()).getName().getValue();
   
    String id="";
    if(route.getProperties() != null)
    {
      List<StringProperty> properties = route.getProperties().getProperties();
      for(StringProperty p : properties)
      {
      	if(p.getName().equals("ID"))
      	{
      		id = p.getValue();
      		break;
      	}
      }
    }
    return new StringBuilder(id).append(destination).append("_").append(gateway).append("_").append(interfaceName).toString();   
  }

}
